package com.yuanlrc.base.service.common;

import io.minio.*;
import io.minio.errors.MinioException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Service
public class MinioService {

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucketName}")
    private String bucketName;

    /**
     * 上传文件到 MinIO
     * @param file 需要上传的文件
     * @throws IOException 文件处理异常
     * @throws MinioException MinIO 异常
     */
    public void uploadFile(MultipartFile file) throws IOException, MinioException {
        // 获取文件名
        String fileName = UUID.randomUUID().toString() + "-" + file.getOriginalFilename();

        // 获取文件的输入流
        InputStream inputStream = file.getInputStream();

        try {
            // 判断目标 bucket 是否存在，若不存在则创建一个新的 bucket
            boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!isExist) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }

            // 上传文件到指定 bucket
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)              // 存储桶名称
                            .object(fileName)                // 文件名
                            .stream(inputStream, file.getSize(), -1)  // 文件流，文件大小
                            .contentType(file.getContentType())       // 文件类型
                            .build()
            );
        } catch (MinioException e) {
            throw new MinioException("MinIO 上传失败: " + e.getMessage());
        } catch (IOException e) {
            throw new IOException("文件读取失败: " + e.getMessage(), e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }
    }
    // 下载文件
    public InputStream downloadFile(String fileName) throws MinioException, IOException, NoSuchAlgorithmException, InvalidKeyException {
        return minioClient.getObject(
                GetObjectArgs.builder()
                        .bucket(bucketName)
                        .object(fileName)
                        .build()
        );
    }
}
